package br.com.pentagrama.service.ui.component;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;

import br.com.pentagrama.service.ui.event.PortChangedEvent;
import br.com.pentagrama.service.ui.event.PortRangeChangedEvent;

public class PortRangeField implements Field {

	private Field startField;
	private int portFieldWidth;
	private Component separator;
	private Field endField;
	
	private String oldStartPort;
	private String oldEndPort;
	
	private JPanel panel;
	
	public PortRangeField(int width, int height, final PortRangeChangedEvent event) {
		panel = new JPanel();
		panel.setPreferredSize(new Dimension(width, height));
		panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
		separator = new JLabel("-");
		oldStartPort = "";
		oldEndPort = "";		
		
		startField = new PortField(portFieldWidth, height, new PortChangedEvent() {
			
			public void updateValue(String value) {
				if (!value.equals(oldStartPort)) {
					oldStartPort = value;
					event.updateValue(value, oldEndPort);
				}
			}
		});
		endField = new PortField(portFieldWidth, height, new PortChangedEvent() {
			
			public void updateValue(String value) {
				if (!value.equals(oldEndPort)) {
					oldEndPort = value;
					event.updateValue(oldStartPort, value);
				}
			}
		});
	}

	public void showIn(Container container) {
		startField.showIn(panel);
		panel.add(Box.createHorizontalStrut(25));
		panel.add(separator);
		panel.add(Box.createHorizontalStrut(25));
		endField.showIn(panel);
		container.add(panel);
	}

}
